package com.iakuil.minio;

import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@Slf4j
@RestController
@RequestMapping("/minio")
public class MinioController {

    private static final String DEFAULT_BUCKET = "foo";

    @Autowired
    private MinioClient minioClient;

    @PostConstruct
    private void init() {
        try {
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(DEFAULT_BUCKET).build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(DEFAULT_BUCKET).build());
                log.info("Bucket {} was created!", DEFAULT_BUCKET);
            }
        } catch (Exception e) {
            log.error("Occurring an exception during bucket initialization!", e);
        }
    }

    @PostMapping("/upload")
    public Object upload(@RequestParam(name = "file") MultipartFile file) {
        long size = file.getSize();
        if (size == 0) {
            return "上传文件不能为空";
        }

        // no need to part if file size less than 5MiB
        boolean isLess5MiB = 5 * 1024 * 1024 > size;
        try {
            InputStream in = file.getInputStream();
            String contentType = file.getContentType();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(DEFAULT_BUCKET)
                    .contentType(contentType)
                    .object(file.getOriginalFilename())
                    .stream(in, isLess5MiB ? size : -1, isLess5MiB ? -1 : size)
                    .build());
        } catch (Exception e) {
            log.error("Occurring an exception during uploading!", e);
        }

        return "{\"status\":10000,\"msg\":\"OK\"}";
    }

    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String fileName) {
        InputStream in = null;
        try {
            StatObjectResponse stat = minioClient.statObject(new StatObjectArgs.Builder()
                    .bucket(DEFAULT_BUCKET)
                    .object(fileName)
                    .build());
            response.setContentType(stat.contentType() == null ? "application/octet-stream; charset=UTF-8" : stat.contentType());
            in = minioClient.getObject(new GetObjectArgs.Builder()
                    .bucket(DEFAULT_BUCKET)
                    .object(fileName)
                    .build());
            IOUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
            log.error("Occurring an exception during downloading!", e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}
